const OsmSource = require('./utils/osm')
const isEmpty = require('lodash/isEmpty')
const sequelize = require('./common/sequelize')
/**
 * 
 * @param {Array} extent [x1,y1,x2,y2]
 * @return {Object}
 */
async function startIndexTile(extent){
    let osm = new OsmSource();
    let xyRange = osm.calculateXYRange(extent);
    let result = {
        miss:[]
    };
    if(isEmpty(xyRange)){
        return;
    }
    for(let rangeInLevel of xyRange){
       let currentResult = await indexTileByRangeInLevel(rangeInLevel);
       if(!isEmpty(currentResult.miss)){
        result.miss = result.miss.concat(currentResult.miss)
       }
    }
    return result;
}
/**
 * 
 * @param {Object} config
 * @param {number} config.level
 * @param {number} config.rowStart
 * @param {number} config.rowEnd
 * @param {number} config.colStart
 * @param {number} config.colEnd
 * @return {Object}
 */
async function indexTileByRangeInLevel({level,rowStart,rowEnd,colStart,colEnd}){
    let result ={
        miss:[]
    }
    for(let row = rowStart;row<=rowEnd;row++){
        for(let col = colStart;col<=colEnd;col++){
            //console.clear();
            //console.log(`level:${level},row:${row},col:${col}`);
            let data = await sequelize.models.RoadIndex.findOne({where:{tile_level:level,tile_row:row,tile_column:col}});
            if(isEmpty(data)){
                result.miss.push({tileLevel:level,tileRow:row,tileColumn:col});
            }
        }
    }
    return result;
}
module.exports.startIndexTile=startIndexTile;